#coding=utf8
import urllib2, re

jsre = re.compile("var total=(\d+?);var volpic='(.*?)';var tpf = (\d+?);var tpf2 = (\d+?);")

tpldic = {
    1:'http://pic.tuku.cc/',
    2:'http://pic2.tuku.cc/',
    3:'http://pic3.tuku.cc/',
    8:'http://pic8.tuku.cc/',
    99:'http://pic99.tuku.cc/',
    1:'http://pic.tuku.cc/',
    2:'http://pic2.tuku.cc/',
    3:'http://pic3.tuku.cc/',
    8:'http://pic8.tuku.cc/8',
    10:'http://pic10.tuku.cc/',
    4:'http://pic4.tuku.cc/',
    7:'http://pic7.tuku.cc/',
    20:'http://tuku.cc/',
    9:'http://pic9.tuku.cc/'
    }

def generate_url(host, path, maxpage, length):
    picurls = []
    length += 1
    for page in range(1, maxpage + 1):
        tp = str(page * 18527)
        if len(tp) < length:
            tp = (length - len(tp)) * '0' + tp
        ptp = (length - len(str(page))) * '0' + str(page)
        # print tp + ptp
        url = host + path + tp + ptp + '.jpg'
        picurls.append(url)
    return picurls

def getpiclist(url, title='unamed', mylog=None):
    "parser html source and js codes to generate piclist"
    try:
        piclist = []
        html = urllib2.urlopen(urllib2.urlparse.urljoin(url + '/', 'index.js')).read()
        result = jsre.findall(html)
        if not result:
            return
        print result
        total = int(result[0][0])
        volpic = result[0][1]
        tpf = int(result[0][2])
        tpf2 = int(result[0][3])

        if not tpldic.has_key(tpf2):
            print 'cannot find host'
            return
        host = tpldic[tpf2]

        for url in generate_url(host, volpic, total, tpf):
            piclist.append([url, url, title])
            
        return piclist
    except  Exception, e:
        if mylog:
            mylog.writeLog(str(e)+'in getpiclist','error')
        else:
            print e
        return None

if __name__ == '__main__':
    # print '\n'.join(generate_url('http://pic.tuku.cc/', 'jj2/mno/glgs/018/', 16, 7))
    print getpiclist('http://www.89890.com/Comic/2490/21')
